package com.yc.springboot.web;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
@ServerEndpoint("/ws/{id}")
public class MyWebSocket {

    // ConcurrentHashMap 线程安全的 Map 集合
    private static Map<String, Session> sessionMap = new ConcurrentHashMap<>();

    // 开启连接
    @OnOpen
    public void onOpen(@PathParam("id") String id, Session session) {
        System.out.println(id + "连接成功!");
        // 将会话保存到容器中
        sessionMap.put(id, session);
        // 将用户id存入会话
        session.getUserProperties().put("id", id);
    }

    // 关闭连接
    @OnClose
    public void onClose(Session session) {
        String id = (String) session.getUserProperties().get("id");
        System.out.println(id + "断开连接!");
        sessionMap.remove(id);
    }

    // 服务器收到消息
    @OnMessage
    public void onMessage(String message, Session session) {
        // 获取发送人 id
        String id = (String) session.getUserProperties().get("id");
        // 群发给其他说的人 or 私发
        //  xxxx            李四:xxxx   => 协议
        final String[] items = message.split(":");
        if (items.length == 1) {
            // 群发
            sessionMap.forEach((_id, _session) -> {
                try {
                    _session.getBasicRemote().sendText(id + "说:" + message);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
        } else {
            // 私发
            sessionMap.forEach((_id, _session) -> {
                // 先查找
                if(items[0].equals(_id)){
                    try {
                        _session.getBasicRemote().sendText(id + "说:" + items[1]);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });
        }

    }

    // 推送定时广告 每隔10秒发送一次
    @Scheduled(cron = "0/10 * * * * ?")
    public void publish(){
        // 群发
        sessionMap.forEach((_id, _session) -> {
            try {
                _session.getBasicRemote().sendText("定时广告: 今天天气寒冷, 注意添加衣服!");
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
    }

}
